#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<time.h>
#include<stdlib.h>

void PrintArry(int* a, int n)
{
	for (int i = 0; i < n; i++)
	{
		printf("%d ", a[i]);
	}
	printf("\n");

}

//最坏：O(N^2)
//最好：O(N)
void InsertSort(int* a, int n)
{
	//多次排序
	for (int i = 1; i < n; i++)
	{
		//int flag = 0;  //假设交换后数组不变

		//单趟排序，在有序区间[0,end]内排序，使数组保持有序
		int end = i - 1;
		int temp = a[end + 1];
		while (end >= 0)
		{
			if (temp < a[end])
			{
				a[end + 1] = a[end];
				end--;  //找到前一个元素比较
				//flag = 1;
			}
			else
			{
				break;
			}
		}
		a[end + 1] = temp;   //break到此处，待插入元素比前一个大或者已经走到数组的头

		//if(flag==1)
		PrintArry(a, n);
	}
}

/*void ShellSort(int* a, int n)
{
	//多次分组
	//gap越大，元素跳动得越大，数组越无序；gap越小，数组越有序
	int gap = n;
	while (gap > 1)  //gap>1预排序，gap=1插入排序
	{
		gap /= 2; //gap/3+1；
		//多组交换
		for (int i = 0; i < n - gap; i++)
		{
			//一组的一次交换
			int end = i;
			int temp = a[i + gap];
			while (end >= 0)
			{
				if (temp < a[end])
				{
					a[end + gap] = a[end];
					end -= gap;
				}
				else
				{
					break;
				}
			}
			a[end + gap] = temp;
		}
		PrintArry(a, n);
	}
}*/

//测试排序性能
/*void TestOP()
{
	srand(time(0));
	const int N = 100000;
	int* a1 = (int*)malloc(sizeof(int) * N);
	int* a2 = (int*)malloc(sizeof(int) * N);
	int* a3 = (int*)malloc(sizeof(int) * N);
	int* a4 = (int*)malloc(sizeof(int) * N);
	int* a5 = (int*)malloc(sizeof(int) * N);
	int* a6 = (int*)malloc(sizeof(int) * N);

	for (int i = 0; i < N; ++i)
	{
		a1[i] = rand();
		a2[i] = a1[i];
		a3[i] = a1[i];
		a4[i] = a1[i];
		a5[i] = a1[i];
		a6[i] = a1[i];
	}

	int begin1 = clock();
	InsertSort(a1, N);
	int end1 = clock();

	int begin2 = clock();
	ShellSort(a2, N);
	int end2 = clock();

	printf("InsertSort:%d\n", end1 - begin1);
	printf("ShellSort:%d\n", end2 - begin2);

	free(a1);
	free(a2);
	free(a3);
	free(a4);
	free(a5);
	free(a6);
}*/



int main()
{
	int a[] = { 2,5,6,9,8,7,3,0,1,4 };
	printf("排序前：\n");
	PrintArry(a, sizeof(a) / sizeof(a[0]));
	printf("排序后：\n");
	InsertSort(a, sizeof(a) / sizeof(a[0]));

	//TestOP();

	return 0;
}